import React from 'react';
import {
  View,
  Text,
  StyleSheet,
  Modal,
  TextInput,
  Platform,
  TouchableNativeFeedback,
  TouchableOpacity,
  TouchableWithoutFeedback,
} from 'react-native';
import {getRealSize} from '../utils';
import ThemeStyles from '../styles';
import PropTypes from 'prop-types';
import Validator from 'async-validator';
import {I18n} from '../reducers/intl';

const Touchable =
  Platform.OS === 'android' ? TouchableNativeFeedback : TouchableOpacity;

export default class InputDialog extends React.Component {
  static propTypes = {
    styles: PropTypes.object,
    visible: PropTypes.bool,
    title: PropTypes.string,
    field: PropTypes.string,
    cancelLabel: PropTypes.string,
    placeholder: PropTypes.string,
    okLabel: PropTypes.string,
    textType: PropTypes.string,
  };
  static defaultProps = {
    styles: {},
    visible: false,
    cancelLabel: I18n.t('button.close'),
    okLabel: I18n.t('button.apply'),
    placeholder: '',
    defaultValue: '',
    field: '',
    textType: 'default',
  };

  state = {
    value: null,
  };

  onClose = () => {
    this.props.onClose();
    this.setState({value: '', error: null});
  };

  componentDidUpdate(prevProps) {
    if (prevProps.visible !== this.props.visible) {
      this.setState({value: this.props.defaultValue || '', error: null});
    }
  }

  onSubmit = async () => {
    // console.log('onSubmit');
    if (this.props.rules) {
      const validator = new Validator(this.props.rules);
      try {
        await validator.validate({[this.props.field]: this.state.value});
        if (this.state.value) {
          this.props.onSubmit(this.state.value);
        }
      } catch (e) {
        // console.log(JSON.stringify(e));
        this.setState({error: e.errors[0].message});
      }
    } else {
      if (this.state.value) {
        this.props.onSubmit(this.state.value);
      }
      this.onClose();
    }
  };

  render() {
    const {
      visible,
      placeholder,
      title,
      defaultValue,
      cancelLabel,
      okLabel,
      textType,
    } = this.props;
    return (
      <Modal animationType="fade" visible={visible} transparent={true}>
        <TouchableWithoutFeedback onPress={this.onClose}>
          <View style={Styles.mask} />
        </TouchableWithoutFeedback>
        <View style={Styles.middle}>
          <TouchableWithoutFeedback onPress={this.onClose}>
            <View style={Styles.mask} />
          </TouchableWithoutFeedback>
          <View style={Styles.background}>
            <View style={Styles.container}>
              {title && <Text style={Styles.title}>{title}</Text>}
              <TextInput
                style={Styles.input}
                blurOnSubmit={true}
                keyboardType={textType}
                onSubmitEditing={this.onSubmit}
                defaultValue={defaultValue}
                placeholder={placeholder}
                underlineColorAndroid="transparent"
                onChangeText={value => this.setState({value, error: null})}
              />
              {this.state.error && (
                <Text style={Styles.error}>{this.state.error}</Text>
              )}
              <View style={Styles.actions}>
                <Touchable onPress={this.onClose} style={{flex: 1}}>
                  <Text style={Styles.button}>{cancelLabel}</Text>
                </Touchable>
                <Touchable onPress={this.onSubmit} style={{flex: 1}}>
                  <Text style={Styles.button}>{okLabel}</Text>
                </Touchable>
              </View>
            </View>
          </View>
          <TouchableWithoutFeedback onPress={this.onClose}>
            <View style={Styles.mask} />
          </TouchableWithoutFeedback>
        </View>
        <TouchableWithoutFeedback onPress={this.onClose}>
          <View style={Styles.mask} />
        </TouchableWithoutFeedback>
      </Modal>
    );
  }
}

const Styles = StyleSheet.create({
  mask: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0, 0.6)',
  },
  middle: {
    flexDirection: 'row',
  },
  background: {
    backgroundColor: 'rgba(0,0,0, 0.6)',
  },
  container: {
    width: getRealSize(288),
    borderRadius: getRealSize(8),
    backgroundColor: '#fff',
  },
  input: {
    backgroundColor: '#F6F6F6',
    margin: getRealSize(8),
    borderRadius: getRealSize(4),
    borderWidth: StyleSheet.hairlineWidth,
    borderColor: '#F6F6F6',
    height: getRealSize(42),
  },
  title: {
    fontSize: getRealSize(18),
    fontWeight: 'bold',
    paddingHorizontal: getRealSize(12),
    paddingTop: getRealSize(8),
  },
  actions: {
    flexDirection: 'row',
    borderTopColor: '#F6F6F6',
    borderTopWidth: 1,
    height: getRealSize(48),
    alignItems: 'center',
    justifyContent: 'center',
  },
  button: {
    flex: 1,
    textAlign: 'center',
    fontSize: getRealSize(16),
    color: ThemeStyles.Color.primary.color,
    paddingVertical: getRealSize(8),
  },
  separator: {},
  error: {
    color: '#e11e1e',
    marginHorizontal: getRealSize(4),
    fontSize: getRealSize(12),
  },
});
